<template>
	<div class="wareHous-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="类型">
					<el-input v-model="state.queryParams.type" placeholder="类型" clearable />
				</el-form-item>
				<el-form-item label="横坐标">
					<el-input v-model="state.queryParams.abscissa" placeholder="横坐标" clearable />
				</el-form-item>

				<el-form-item>
					<el-button-group>

						<el-button type="primary" icon="ele-Search" @click="handleQuery" > 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>


					</el-button-group>
					<el-button-group>
						<el-button type="primary" icon="ele-Plus" @click="addWare"
							>添加</el-button>
						<el-button type="primary" icon="ele-Download" @click="downloadTemplate"
							>模版</el-button>
						<el-button type="danger"  icon="ele-Warning"
							@click="batchDeleteMaintenance">批量删除</el-button>

						<el-button type="primary" icon="ele-Download" @click="exportDate"
							>导出</el-button>


					</el-button-group>

				</el-form-item>

				<el-form-item>

					<el-button-group>
						<el-upload class="upload-demo" :http-request="handleUpload" :show-file-list="false"
							:before-upload="beforeUpload" :on-success="handleUploadSuccess"
							:on-error="handleUploadError">
							<el-button icon="ele-Upload" >导入</el-button>
						</el-upload>

					</el-button-group>
				</el-form-item>
				<!-- <el-button-group>
						<el-button type="primary" icon="ele-Download" @click="downloadTemplate"
							>模版</el-button>
					</el-button-group> -->



				<!-- <el-form-item>
					 <el-upload>
							<el-button type="primary" icon="ele-Upload" @click="ImportWare"
								 style="margin-bottom: -70px;">导入1</el-button>
							<input ref="fileInput" type="file" hidden accept=".xlsx,.xls" @change="ImportWare" />
						</el-upload> 
	
				</el-form-item> -->

			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.Maintenance" style="width: 100%" v-loading="state.loading" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" prop="id" width="55" align="center" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="type" label="类型" align="center" show-overflow-tooltip />
				<el-table-column prop="abscissa" label="横坐标" align="center" show-overflow-tooltip />
				<el-table-column prop="coordinate" label="纵坐标" align="center" show-overflow-tooltip />
				<el-table-column prop="vertical" label="垂直坐标" align="center" show-overflow-tooltip />
				<el-table-column prop="point" label="对应点位" align="center" show-overflow-tooltip />
				<el-table-column prop="explanatory" label="描述" align="center" show-overflow-tooltip />
				<el-table-column prop="enable" label="启用状态" width="80" align="center">
					<template #default="scope">
						<el-tag v-if="scope.row.enable === 1"> 启用 </el-tag>
						<el-tag type="danger" v-else> 未启用 </el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="140" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditWarehous(scope.row)"
							> 编辑 </el-button>
						<el-button size="small" text type="danger" @click="delWarehous(scope.row)"
							> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditMainten ref="editMaintenRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="wareHous">
import { onMounted, computed, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, makeInstaller } from 'element-plus';
import { getAPI } from '/@/utils/axios-utils';
import { useRoute } from 'vue-router'; // 导入路由
import EditMainten from './component/editMainten.vue';



import { MaintenanceinportApi, GetMaintenanceApi, MaintenanceexportApi,BatchDeleteMaintenanceApi, DownloadMaintenanceApi } from '/@/api-services/apis/warehouse-maintenance-api'; // 导入 API 服务
import { Maintenance, DeleteMaintenance } from '../../../api-services/models/warehouse-input-maintenance'; // 导入获取实体
import { downloadByData, getFileName } from '/@/utils/download';

const editMaintenRef = ref<InstanceType<typeof EditMainten>>();
const state = reactive({
	loading: false,
	Maintenance: [] as Array<Maintenance>,
	queryParams: {
		abscissa: undefined,
		type: undefined,
	},

	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editWarehousTitle: '',

});

onMounted(async () => {
	//console.log('当前路由参数:', route); // 添加路由参数调试
	handleQuery();

});

const resetQuery = () => {
	state.queryParams.abscissa = undefined
	state.queryParams.type = undefined
	handleQuery();
};
// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {

		const res = await GetMaintenanceApi({
			...state.queryParams,
			page: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.Maintenance = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.Maintenance = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};
// 打开新增页面

const addWare = () => {
	const addData = {
		description: null,
		total: null,
		attachment: null,
		isenable: 1,
	};
	state.editWarehousTitle = '添加维护信息';
	editMaintenRef.value?.openDialog(addData);
};

// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editWarehousTitle = '编辑维护信息';
	editMaintenRef.value?.openDialog(row);
};

// 假设存在一个方法可以获取选中行的数据，这里我们先定义一个 ref 来存储选中的行
const multipleSelection = ref<DeleteMaintenance[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 获取选中行的 idlist
const selectedIds = computed(() => multipleSelection.value.map(item => ({ id: item.id })));

const batchDeleteMaintenance = async () => {
	if (selectedIds.value.length === 0) {
		ElMessage.warning('请选择要删除的行');
		return;
	}
	console.log(selectedIds.value);
	try {
		await BatchDeleteMaintenanceApi(selectedIds.value);
		handleQuery(); // 刷新表格数据
		ElMessage.success('批量删除成功');
	} catch (error) {
		ElMessage.error('批量删除失败');
	}
};

const delWarehous = async (row: any) => {
	// 为了避免提示框显示慢的问题，提前处理确认逻辑，使用更简洁的方式调用提示框
	ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		try {
			interface ItemWithId { id: number; }
			const itemWithId: ItemWithId = { id: row.id };
			await BatchDeleteMaintenanceApi([itemWithId]);
			handleQuery();
			ElMessage.success('删除成功');
		}
		catch (error) {
			//.error('删除失败:', error);
			ElMessage.error('删除失败，请稍后重试');
		}

	}).catch(() => {
		ElMessage.info('已取消删除');
	});
};

// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
	const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
		file.type === 'application/vnd.ms-excel'
	if (!isExcel) {
		ElMessage.error('只能上传 Excel 文件!')
		return false
	}
	return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
	const formData = new FormData()
	formData.append('file', options.file)
	// 这里调用你的上传API
	//console.log('handleUpload', formData);
	try {

		const response = await MaintenanceinportApi(formData).then((response) => {
			console.log('response', response);
			handleUploadSuccess(response);

		})

	} catch (error) {
		console.log('error', error);
		handleUploadError(error);
	}
}
const downloadTemplate = async () => {
	try {
		DownloadMaintenanceApi().then((response) => {

			const blob = new Blob([response.data])
			const fileName = getFileName(response.headers);
			downloadByData(response.data as any, fileName);

			ElMessage.success(`下载成功${fileName}`);
		}); // 调用下载模板的API

	} catch (error) {
		ElMessage.error('下载失败');
	}
};

// 上传成功回调
const handleUploadSuccess = async (response: any) => {
	console.log('response', response);
	if (response.status === 200) {
		ElMessage.success('导入成功')
		handleQuery() // 刷新表格数据
	}
	else {
		ElMessage.error(response.message || '导入失败')
	}
}

// 上传失败回调
const handleUploadError = (error: any) => {
	ElMessage.error(error.message || '导入失败' + error.message)
}

const exportDate = async () => {
	try {
		state.loading = true;
		// 通常导出文件时需要设置 responseType 为 'blob'，以正确处理二进制数据
		// 为了解决类型不匹配问题，将 responseType 单独传递
		const config = { responseType: 'blob' };
		var res = await MaintenanceexportApi(state.queryParams);
		state.loading = false;
		var fileName = getFileName(res.headers);
		// 假设增加一些日志记录，方便调试
		console.log('准备开始下载文件，文件数据:', res.data, '文件名:', fileName);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
}

// 改变页面容量


const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

</script>